﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using Syx.Webapi.AppCode.Models;
using Syx.Webapi.AppCode.Exceptions;
using Syx.Webapi.AppCode.Extensions;
using ZhongLiang.Core.Helpers;

namespace Syx.Webapi.AppCode.Filters {
    public class RazorPageExceptionFilter : IExceptionFilter {

        private readonly ILogger<RazorPageExceptionFilter> _logger;

        public RazorPageExceptionFilter(ILogger<RazorPageExceptionFilter> logger) {
            _logger = logger;
        }


        public void OnException(ExceptionContext context) {
            var exception = context.Exception;
            //if (exception is MessageBox error) {
            //    context.ExceptionHandled = true;
            //    context.HttpContext.Response.StatusCode = 200;
            //    context.Result = new JsonResult(error.GetApiResult());
            //    return;
            //}
            if (context.HttpContext.Request.IsAjaxRequest()) {
                if (exception is InfoException error21) {
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = 200;
                    context.Result = new JsonResult(new ApiResultData().ResultWarnMessage(error21.Message));
                    return;
                }
                if (exception is WarnException error2) {
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = 200;
                    context.Result = new JsonResult(new ApiResultData().ResultWarn(error2.Message, null));
                    return;
                }
                if (exception is UnauthorizedException error3) {
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = 200;
                    context.Result = new JsonResult(ApiResult.ResultMessage(ApiResultCodeEnum.UnAuth, "未登录!"));
                    return;
                }

                if (context.HttpContext.Response.StatusCode == (int)HttpStatusCode.Unauthorized) {
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = 200;
                    context.Result = new JsonResult(ApiResult.ResultMessage(ApiResultCodeEnum.UnAuth, "未授权!"));
                    return;
                }

                //nlog 写入日志到 txt
                _logger.LogError(exception, context.HttpContext.Connection.RemoteIpAddress?.ToString());
                //var message = $"服务端出现异常![异常消息：{exception.Message}]";
                var message = $"服务端出现异常![异常消息：未知异常，请查看服务器日志]";
                NlogHelper._logger.Error(exception);
                var apiResult = ApiResult.ResultMessage(ApiResultCodeEnum.Error, message);
                context.Result = new JsonResult(apiResult);
            }
        }
    }
}
